import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { StorageService } from '../services/storage.service';

interface AuthGuardProps extends RouteProps {
  component: React.ComponentType<any>;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ component: Component, ...rest }) => {
  const [isAuthenticated, setIsAuthenticated] = React.useState<boolean | null>(null);

  React.useEffect(() => {
    const checkAuth = async () => {
      const token = await StorageService.get('auth_token');
      setIsAuthenticated(!!token);
    };
    checkAuth();
  }, []);

  if (isAuthenticated === null) {
    return null; // Or loading spinner
  }

  return (
    <Route
      {...rest}
      render={props =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};

export default AuthGuard;